﻿namespace Ymatou.UserAuth.Agent.Sso
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web;
    using Ymatou.UserAuth.Extension;

    /// <summary>
    /// sso 客户端签名校验module （使用 ClientCallbackHandler）
    /// </summary>
    [Obsolete("使用 ClientCallbackHandler",true)]
    public class CCheckSignModule : IHttpModule
    {

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += context_BeginRequest;
        }

        void context_BeginRequest(object sender, EventArgs e)
        {

            var context = ((HttpApplication)sender).Context;
            if (context == null) return;
            var token = context.Request[ConstParameter.QueryToken];
            if (string.IsNullOrEmpty(token))
            {
                context.Response.Redirect("/", false);
                return;
            }
            var _timeOutVal = System.Configuration.ConfigurationManager.AppSettings["TokenTimeOut"];
            var __timeOut = string.IsNullOrEmpty(_timeOutVal) ? null : (DateTime?)DateTime.Now.Add(TimeSpan.Parse(_timeOutVal));
            context.Response.SetCookie(ConstParameter.SSOCOOKIEKEY_CLIENT_SIGN, token, domain: SSOClient.SubDomain(context.Request.Url.Host)/*, httpOnly: true*/, expires: __timeOut);

            var _returnUrl = context.Request[ConstParameter.ReturnUrl];
            if (!string.IsNullOrEmpty(_returnUrl))
                _returnUrl = _returnUrl.RemoveQueryStringKey(ConstParameter.QueryToken);
            else
                _returnUrl = "/";
            context.Response.Redirect(_returnUrl, false);
            #region
            // SSOClient.CheckSign(token
            //, toke => new UserLoginAuthAgent().RequestTokenAuth(token)
            //, (e1, e2) => new UserLoginAuthAgent().CheckSign(e1, e2).Success
            //, userID =>
            //{
            //    new UserLoginAuthAgent().GetBuserBills(userID);
            //    var _timeOutVal = System.Configuration.ConfigurationManager.AppSettings["SSOCookieTimeOut"];
            //    var __timeOut = string.IsNullOrEmpty(_timeOutVal) ? null : (DateTime?)DateTime.Now.Add(TimeSpan.Parse(_timeOutVal));
            //    context.Response.SetCookie(ConstParameter.SSOCOOKIEKEY_CLIENT_SIGN, token, domain: SSOClient.SubDomain(context.Request.Url.Host), httpOnly: true, expires: __timeOut);
            //    context.Response.Redirect("/",false);
            //});
            #endregion
        }
    }
}
